import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isEmpty from "lodash/isEmpty";
var _excluded = ["locale", "count", "timeZone"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _class, _class2;

/**
 * @reactProps {!function} fetchCount - 获取消息数量
 * @reactProps {!function} gotoTab - 消息点击事件出发的页面跳转
 * @reactProps {!function} fetchNotices - 获取消息
 */
import React from 'react';
import { Badge, Icon, Tooltip, Popover, Spin, Tabs, Button } from 'antd';
import { connect } from 'dva';
import { Bind } from 'lodash-decorators';
import monent from 'moment';
import classNames from 'classnames';
import { routerRedux } from 'dva/router';
import intl from "../../../utils/intl";
import { getResponse } from "../../../utils/utils";
import { timeZone2MomentUTC } from "../../../utils/renderer";
import { allRead, deleteAll, queryNotices, queryAnnounces } from "../../../services/api";
import emptyMessageIcon from "../../../assets/empty-message.png";
import List from "./NoticeList";
import styles from "./index.less?modules";
var TabPane = Tabs.TabPane;
var noCountOffset = [-2, 0];
var countLt10Offset = [18, 2];
var countGt10Offset = [18, 4];
var DefaultNoticeIcon = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), (_class = (_class2 = /*#__PURE__*/function (_React$PureComponent) {
  _inherits(DefaultNoticeIcon, _React$PureComponent);

  var _super = _createSuper(DefaultNoticeIcon);

  function DefaultNoticeIcon(props) {
    var _this;

    _classCallCheck(this, DefaultNoticeIcon);

    _this = _super.call(this, props);

    _this.handleItemClick = function (item) {
      var gotoTab = _this.props.gotoTab;

      switch (item.userMessageTypeCode) {
        case 'NOTICE':
          gotoTab({
            pathname: "/cmsg/user-message/detail/notice/".concat(item.id)
          });
          break;

        case 'ANNOUNCE':
          gotoTab({
            pathname: "/cmsg/user-message/detail/announce/".concat(item.id)
          });
          break;

        case 'MSG':
          gotoTab({
            pathname: "/cmsg/user-message/detail/message/".concat(item.id)
          });
          break;

        default:
          // should throw error, unKnow message type,
          break;
      }

      _this.setState({
        visible: false
      });
    };

    _this.handleAnnounceItemClick = function (item) {
      var gotoTab = _this.props.gotoTab;
      gotoTab({
        pathname: "/cmsg/user-message/detail/announce/".concat(item.id)
      });
    };

    _this.handleNoticeVisibleChange = function (visible) {
      _this.setState({
        visible: visible
      });

      if (visible) {
        _this.fetchNotices();

        _this.fetchAnnounces();
      }
    };

    _this.onTabChange = function (tabType) {
      _this.setState({
        tabType: tabType
      });

      _this.props.onTabChange(tabType);
    };

    var title = props.title;
    _this.state = {
      visible: false,
      currentTab: 'NOTICE' // 当前tab页

    };

    if (title) {
      _this.state.tabType = title;
    }

    return _this;
  }

  _createClass(DefaultNoticeIcon, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var fetchCount = this.props.fetchCount;
      fetchCount();
    }
  }, {
    key: "render",
    value: function render() {
      var _classNames;

      var _this$props = this.props,
          className = _this$props.className,
          count = _this$props.count;
      var noticeButtonClass = classNames((_classNames = {}, _defineProperty(_classNames, className, true), _defineProperty(_classNames, styles.noticeButton, true), _defineProperty(_classNames, styles.hasCount, count > 0), _classNames));
      var offset = noCountOffset;

      if (count > 9) {
        offset = countGt10Offset;
      } else if (count > 0) {
        offset = countLt10Offset;
      }

      var notificationBox = this.getNotificationBox();
      var visible = this.state.visible;
      var bellIconClass = visible ? "".concat(styles['icon-active'], " ").concat(styles['notification-icon']) : styles['notification-icon'];
      var trigger = /*#__PURE__*/React.createElement("span", {
        className: noticeButtonClass
      }, /*#__PURE__*/React.createElement(Badge, {
        count: count,
        className: styles.badge,
        offset: offset
      }, /*#__PURE__*/React.createElement(Icon, {
        className: bellIconClass
      })));

      if (!notificationBox) {
        return trigger;
      }

      return /*#__PURE__*/React.createElement(Popover, {
        placement: "bottomRight",
        content: notificationBox,
        popupClassName: styles.popover,
        trigger: "click",
        arrowPointAtCenter: true,
        onVisibleChange: this.handleNoticeVisibleChange,
        visible: visible
      }, trigger);
    }
    /**
     * 点击查看更多跳转页面
     */

  }, {
    key: "handleNoticeList",
    value: function handleNoticeList(e) {
      e.preventDefault();
      var gotoTab = this.props.gotoTab;
      gotoTab({
        pathname: "/cmsg/user-message/list"
      });
      this.setState({
        visible: false
      });
    }
    /**
     * 点击查看更多跳转页面
     */

  }, {
    key: "handleNoticeItem",
    value: function handleNoticeItem(e) {
      e.preventDefault();
      this.setState({
        visible: false
      });
    }
    /**
     * 点击每一行跳转到详情界面
     */

  }, {
    key: "handleChangeTab",
    value: function handleChangeTab(type) {
      this.setState({
        currentTab: type
      });

      switch (type) {
        case 'NOTICE':
          this.fetchNotices();
          break;

        case 'ANNOUNCE':
          this.fetchAnnounces();
          break;

        default:
      }
    }
    /**
     * 清除全部消息
     */

  }, {
    key: "handleDeleteAll",
    value: function () {
      var _handleDeleteAll = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return deleteAll();

              case 2:
                _context.next = 4;
                return this.fetchNotices();

              case 4:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function handleDeleteAll() {
        return _handleDeleteAll.apply(this, arguments);
      }

      return handleDeleteAll;
    }()
    /**
     * 获取公告数据
     */

  }, {
    key: "fetchAnnounces",
    value: function fetchAnnounces() {
      var _this2 = this;

      this.setState({
        fetchingAnnounces: true
      });
      queryAnnounces({
        previewCount: 3
      }).then(function (res) {
        var data = getResponse(res);

        _this2.setState({
          announces: data,
          fetchingAnnounces: false
        });
      });
    }
    /**
     * 获取消息数据
     */

  }, {
    key: "fetchNotices",
    value: function fetchNotices() {
      var _this3 = this;

      this.setState({
        fetchingNotices: true
      });
      queryNotices({
        previewMessageCount: 3,
        readFlag: 0
      }).then(function (res) {
        var data = getResponse(res);

        _this3.setState({
          notices: data,
          fetchingNotices: false
        });
      });
    }
    /**
     * 已读全部消息
     */

  }, {
    key: "handleAllRead",
    value: function () {
      var _handleAllRead = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return allRead({
                  readAll: 1
                });

              case 2:
                _context2.next = 4;
                return this.fetchNotices();

              case 4:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function handleAllRead() {
        return _handleAllRead.apply(this, arguments);
      }

      return handleAllRead;
    }()
  }, {
    key: "getNotificationBox",
    value: function getNotificationBox() {
      var _this4 = this;

      var _this$props2 = this.props,
          locale = _this$props2.locale,
          count = _this$props2.count,
          timeZone = _this$props2.timeZone,
          childProps = _objectWithoutProperties(_this$props2, _excluded);

      if (_isEmpty(childProps)) {
        return null;
      }

      var emptyImage = childProps.emptyImage,
          title = childProps.title;
      var _this$state = this.state,
          currentTab = _this$state.currentTab,
          announces = _this$state.announces,
          notices = _this$state.notices,
          _this$state$fetchingN = _this$state.fetchingNotices,
          fetchingNotices = _this$state$fetchingN === void 0 ? false : _this$state$fetchingN,
          _this$state$fetchingA = _this$state.fetchingAnnounces,
          fetchingAnnounces = _this$state$fetchingA === void 0 ? false : _this$state$fetchingA; // TODO: 需要之后审查下为什么这里需要自己转化一下数据结构

      var newNotices = notices && notices.map(function (item) {
        var utc = timeZone2MomentUTC[timeZone] || (timeZone2MomentUTC[timeZone] === 0 ? 0 : 8);
        return {
          id: item.userMessageId,
          key: "".concat(item.userMessageTypeCode, "_").concat(item.userMessageId),
          title: item.subject,
          datetime: monent("".concat(item.creationDate)).utcOffset(utc, true).fromNow(),
          userMessageTypeMeaning: item.userMessageTypeMeaning,
          userMessageTypeCode: item.userMessageTypeCode // avatar: messageIcon,

        };
      });
      var newAnnounces = Array.isArray(announces) ? announces.map(function (item) {
        var utc = timeZone2MomentUTC[timeZone] || (timeZone2MomentUTC[timeZone] === 0 ? 0 : 8);
        return {
          id: item.noticeId,
          key: "".concat(item.receiverTypeCode, "_").concat(item.noticeId),
          title: item.title,
          datetime: monent("".concat(item.publishedDate)).utcOffset(utc, true).fromNow(),
          userMessageTypeMeaning: item.receiverTypeMeaning,
          userMessageTypeCode: item.noticeTypeCode // avatar: messageIcon,

        };
      }) : [];
      var panes = /*#__PURE__*/React.createElement(List, {
        data: newNotices,
        onClick: this.handleItemClick,
        onClear: function onClear() {
          return _this4.props.onClear(title);
        },
        onMore: this.handleNoticeList,
        locale: locale // 以下为item的内容
        ,
        title: title,
        emptyImage: emptyImage,
        contentItemAction: this.handleNoticeItem,
        contentTitleAction: /*#__PURE__*/React.createElement("a", {
          onClick: this.handleNoticeList
        }, intl.get('cpaas.common.basicLayout.gotoUserMessage').d('进入消息中心'))
      });
      var announcePanes = /*#__PURE__*/React.createElement(List, {
        data: newAnnounces,
        onClick: this.handleAnnounceItemClick,
        locale: locale // 以下为item的内容
        ,
        title: title,
        emptyImage: emptyImage,
        contentItemAction: this.handleNoticeItem,
        contentTitleAction: /*#__PURE__*/React.createElement("a", {
          onClick: this.handleNoticeList
        }, intl.get('cpaas.common.basicLayout.gotoUserMessage').d('进入消息中心'))
      });
      var operations = /*#__PURE__*/React.createElement("div", {
        className: styles['icon-btns']
      }, /*#__PURE__*/React.createElement(Tooltip, {
        title: intl.get('cpaas.common.basicLayout.option.allRead').d('全部已读')
      }, /*#__PURE__*/React.createElement(Button, {
        shape: "circle",
        className: styles['icon-button'],
        onClick: this.handleAllRead
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "mail",
        style: {
          fontSize: 16
        }
      }))), /*#__PURE__*/React.createElement(Tooltip, {
        title: intl.get('cpaas.common.basicLayout.option.deleteAll').d('全部清除')
      }, /*#__PURE__*/React.createElement(Button, {
        shape: "circle",
        className: styles['icon-button'],
        onClick: this.handleDeleteAll
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "delete",
        style: {
          fontSize: 16
        }
      }))));
      return /*#__PURE__*/React.createElement(Tabs, {
        defaultActiveKey: "NOTICE",
        animated: false,
        onChange: this.handleChangeTab,
        tabBarExtraContent: currentTab === 'NOTICE' ? operations : '',
        className: styles['layout-tabs']
      }, /*#__PURE__*/React.createElement(TabPane, {
        tab: /*#__PURE__*/React.createElement(Badge, {
          count: count
        }, " ", intl.get('cpaas.common.view.title.tabNotice').d('消息')),
        key: "NOTICE"
      }, /*#__PURE__*/React.createElement(Spin, {
        spinning: fetchingNotices,
        delay: 0
      }, fetchingNotices ? /*#__PURE__*/React.createElement("div", {
        style: {
          height: '258px'
        }
      }) : panes)), /*#__PURE__*/React.createElement(TabPane, {
        tab: /*#__PURE__*/React.createElement(Badge, null, intl.get('cpaas.common.view.title.tabAnnounce').d('公告')),
        key: "ANNOUNCE"
      }, /*#__PURE__*/React.createElement(Spin, {
        spinning: fetchingAnnounces,
        delay: 0
      }, fetchingAnnounces ? /*#__PURE__*/React.createElement("div", {
        style: {
          height: '258px'
        }
      }) : announcePanes)));
    }
  }]);

  return DefaultNoticeIcon;
}(React.PureComponent), _class2.defaultProps = {
  emptyImage: emptyMessageIcon
}, _class2), (_applyDecoratedDescriptor(_class.prototype, "handleNoticeList", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "handleNoticeList"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleNoticeItem", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "handleNoticeItem"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleChangeTab", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "handleChangeTab"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleDeleteAll", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "handleDeleteAll"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "fetchAnnounces", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "fetchAnnounces"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "fetchNotices", [_dec6], Object.getOwnPropertyDescriptor(_class.prototype, "fetchNotices"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleAllRead", [_dec7], Object.getOwnPropertyDescriptor(_class.prototype, "handleAllRead"), _class.prototype)), _class));
export default connect(function (_ref) {
  var _ref$global = _ref.global,
      global = _ref$global === void 0 ? {} : _ref$global,
      _ref$user = _ref.user,
      user = _ref$user === void 0 ? {} : _ref$user;
  return {
    count: global.count,
    timeZone: user.currentUser.timeZone
  };
}, function (dispatch) {
  return {
    // 跳转到页面
    gotoTab: function gotoTab(location, state) {
      return dispatch(routerRedux.push(location, state));
    },
    // 获取消息数量
    fetchCount: function fetchCount() {
      return dispatch({
        type: 'global/fetchCount'
      });
    },
    deleteAll: function deleteAll() {
      return dispatch({
        type: 'global/deleteAll'
      });
    },
    allRead: function allRead(payload) {
      return dispatch({
        type: 'global/allRead',
        payload: payload
      });
    }
  };
})(DefaultNoticeIcon);